/*
 * @Author: 彭林
 * @Date: 2021-05-14 17:50:49
 * @LastEditTime: 2021-07-14 18:23:53
 * @LastEditors: 彭林
 * @Description:
 * @FilePath: /saas-app/app/service/subject.go
 */
package service

import (
	"saas-app/app/dao"
	"saas-app/app/model"
	"unicode/utf8"

	"github.com/gogf/gf/database/gdb"
)

type SubjectRepository interface {
	GetSubjectList(school_id, campus_id, page, limit int) (subjectList gdb.Result, total int)
	UpdateSubject(subject_id uint, data map[string]interface{}) bool
	CreateSubject(school_id, campus_id uint, subject *model.Subject) bool
}

type subject struct{}

func SubjectService() SubjectRepository {
	return &subject{}
}

func (s subject) GetSubjectList(school_id, campus_id, page, limit int) (subjectList gdb.Result, total int) {

	db := dao.Subject.Where("school_id = ?", school_id).Where("campus_id = ?", campus_id)

	total, err := db.FindCount()

	if err != nil {
		panic(err)
	}

	if page > 0 && limit > 0 {
		db = db.Offset((page - 1) * limit).Limit(limit)
	}

	subjectList, err = db.FindAll()

	if err != nil {
		panic(err)
	}

	return subjectList, total
}

func (s subject) UpdateSubject(subject_id uint, data map[string]interface{}) bool {

	if subject_id <= 0 {
		panic("参数错误")
	}

	if data["subject_name"] != nil && utf8.RuneCountInString(data["subject_name"].(string)) > 20 {
		panic("参数错误 subject_name")
	}

	if data["remark"] != nil && utf8.RuneCountInString(data["remark"].(string)) > 100 {
		panic("参数错误 remark")
	}

	if _, err := dao.Subject.Where("id = ?", subject_id).Update(data); err != nil {
		panic(err)
	}
	return true

}

func (s subject) CreateSubject(school_id, campus_id uint, subject *model.Subject) bool {

	_, err := dao.Subject.Save(subject)

	if err != nil {
		panic(err)
	}

	return true
}
